Merge "rdbms: make LBFactory close/rollback dangling handles like LoadBalancer"
[lhc/web/wiklou.git] / includes / libs / rdbms / loadbalancer / LoadBalancer.php
1 <?php
2 /**
3 * Database load balancing manager
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
19 *
20 * @file
21 */
22 namespace Wikimedia\Rdbms;
23
24 use Psr\Log\LoggerInterface;
25 use Psr\Log\NullLogger;
26 use Wikimedia\ScopedCallback;
27 use BagOStuff;
28 use EmptyBagOStuff;
29 use WANObjectCache;
30 use ArrayUtils;
31 use LogicException;
32 use UnexpectedValueException;
33 use InvalidArgumentException;
34 use RuntimeException;
35 use Exception;
36
37 /**
38 * Database connection, tracking, load balancing, and transaction manager for a cluster
39 *
40 * @ingroup Database
41 */
42 class LoadBalancer implements ILoadBalancer {
43 /** @var ILoadMonitor */
44 private $loadMonitor;
45 /** @var callable|null Callback to run before the first connection attempt */
46 private $chronologyCallback;
47 /** @var BagOStuff */
48 private $srvCache;
49 /** @var WANObjectCache */
50 private $wanCache;
51 /** @var mixed Class name or object With profileIn/profileOut methods */
52 private $profiler;
53 /** @var TransactionProfiler */
54 private $trxProfiler;
55 /** @var LoggerInterface */
56 private $replLogger;
57 /** @var LoggerInterface */
58 private $connLogger;
59 /** @var LoggerInterface */
60 private $queryLogger;
61 /** @var LoggerInterface */
62 private $perfLogger;
63 /** @var callable Exception logger */
64 private $errorLogger;
65 /** @var callable Deprecation logger */
66 private $deprecationLogger;
67
68 /** @var DatabaseDomain Local DB domain ID and default for selectDB() calls */
69 private $localDomain;
70
71 /** @var Database[][][] Map of (connection category => server index => IDatabase[]) */
72 private $conns;
73
74 /** @var array[] Map of (server index => server config array) */
75 private $servers;
76 /** @var array[] Map of (group => server index => weight) */
77 private $groupLoads;
78 /** @var bool Whether to disregard replica DB lag as a factor in replica DB selection */
79 private $allowLagged;
80 /** @var int Seconds to spend waiting on replica DB lag to resolve */
81 private $waitTimeout;
82 /** @var array The LoadMonitor configuration */
83 private $loadMonitorConfig;
84 /** @var string Alternate local DB domain instead of DatabaseDomain::getId() */
85 private $localDomainIdAlias;
86 /** @var int Amount of replication lag, in seconds, that is considered "high" */
87 private $maxLag;
88 /** @var string|null Default query group to use with getConnection() */
89 private $defaultGroup;
90
91 /** @var string Current server name */
92 private $hostname;
93 /** @var bool Whether this PHP instance is for a CLI script */
94 private $cliMode;
95 /** @var string Agent name for query profiling */
96 private $agent;
97
98 /** @var array[] $aliases Map of (table => (dbname, schema, prefix) map) */
99 private $tableAliases = [];
100 /** @var string[] Map of (index alias => index) */
101 private $indexAliases = [];
102 /** @var array[] Map of (name => callable) */
103 private $trxRecurringCallbacks = [];
104
105 /** @var Database Connection handle that caused a problem */
106 private $errorConnection;
107 /** @var int[] The group replica server indexes keyed by group */
108 private $readIndexByGroup = [];
109 /** @var bool|DBMasterPos Replication sync position or false if not set */
110 private $waitForPos;
111 /** @var bool Whether the generic reader fell back to a lagged replica DB */
112 private $laggedReplicaMode = false;
113 /** @var string The last DB selection or connection error */
114 private $lastError = 'Unknown error';
115 /** @var string|bool Reason this instance is read-only or false if not */
116 private $readOnlyReason = false;
117 /** @var int Total number of new connections ever made with this instance */
118 private $connectionCounter = 0;
119 /** @var bool */
120 private $disabled = false;
121 /** @var bool Whether any connection has been attempted yet */
122 private $connectionAttempted = false;
123
124 /** var int An identifier for this class instance */
125 private $id;
126 /** @var int|null Integer ID of the managing LBFactory instance or null if none */
127 private $ownerId;
128 /** @var string|bool Explicit DBO_TRX transaction round active or false if none */
129 private $trxRoundId = false;
130 /** @var string Stage of the current transaction round in the transaction round life-cycle */
131 private $trxRoundStage = self::ROUND_CURSORY;
132
133 /** @var int Warn when this many connection are held */
134 const CONN_HELD_WARN_THRESHOLD = 10;
135
136 /** @var int Default 'maxLag' when unspecified */
137 const MAX_LAG_DEFAULT = 6;
138 /** @var int Default 'waitTimeout' when unspecified */
139 const MAX_WAIT_DEFAULT = 10;
140 /** @var int Seconds to cache master DB server read-only status */
141 const TTL_CACHE_READONLY = 5;
142
143 const KEY_LOCAL = 'local';
144 const KEY_FOREIGN_FREE = 'foreignFree';
145 const KEY_FOREIGN_INUSE = 'foreignInUse';
146
147 const KEY_LOCAL_NOROUND = 'localAutoCommit';
148 const KEY_FOREIGN_FREE_NOROUND = 'foreignFreeAutoCommit';
149 const KEY_FOREIGN_INUSE_NOROUND = 'foreignInUseAutoCommit';
150
151 /** @var string Transaction round, explicit or implicit, has not finished writing */
152 const ROUND_CURSORY = 'cursory';
153 /** @var string Transaction round writes are complete and ready for pre-commit checks */
154 const ROUND_FINALIZED = 'finalized';
155 /** @var string Transaction round passed final pre-commit checks */
156 const ROUND_APPROVED = 'approved';
157 /** @var string Transaction round was committed and post-commit callbacks must be run */
158 const ROUND_COMMIT_CALLBACKS = 'commit-callbacks';
159 /** @var string Transaction round was rolled back and post-rollback callbacks must be run */
160 const ROUND_ROLLBACK_CALLBACKS = 'rollback-callbacks';
161 /** @var string Transaction round encountered an error */
162 const ROUND_ERROR = 'error';
163
164 public function __construct( array $params ) {
165 if ( !isset( $params['servers'] ) || !count( $params['servers'] ) ) {
166 throw new InvalidArgumentException( 'Missing or empty "servers" parameter' );
167 }
168
169 $listKey = -1;
170 $this->servers = [];
171 $this->groupLoads = [ self::GROUP_GENERIC => [] ];
172 foreach ( $params['servers'] as $i => $server ) {
173 if ( ++$listKey !== $i ) {
174 throw new UnexpectedValueException( 'List expected for "servers" parameter' );
175 }
176 $this->servers[$i] = $server;
177 foreach ( ( $server['groupLoads'] ?? [] ) as $group => $ratio ) {
178 $this->groupLoads[$group][$i] = $ratio;
179 }
180 $this->groupLoads[self::GROUP_GENERIC][$i] = $server['load'];
181 }
182
183 $localDomain = isset( $params['localDomain'] )
184 ? DatabaseDomain::newFromId( $params['localDomain'] )
185 : DatabaseDomain::newUnspecified();
186 $this->setLocalDomain( $localDomain );
187
188 $this->waitTimeout = $params['waitTimeout'] ?? self::MAX_WAIT_DEFAULT;
189
190 $this->conns = self::newTrackedConnectionsArray();
191 $this->waitForPos = false;
192 $this->allowLagged = false;
193
194 if ( isset( $params['readOnlyReason'] ) && is_string( $params['readOnlyReason'] ) ) {
195 $this->readOnlyReason = $params['readOnlyReason'];
196 }
197
198 $this->maxLag = $params['maxLag'] ?? self::MAX_LAG_DEFAULT;
199
200 $this->loadMonitorConfig = $params['loadMonitor'] ?? [ 'class' => 'LoadMonitorNull' ];
201 $this->loadMonitorConfig += [ 'lagWarnThreshold' => $this->maxLag ];
202
203 $this->srvCache = $params['srvCache'] ?? new EmptyBagOStuff();
204 $this->wanCache = $params['wanCache'] ?? WANObjectCache::newEmpty();
205 $this->profiler = $params['profiler'] ?? null;
206 $this->trxProfiler = $params['trxProfiler'] ?? new TransactionProfiler();
207
208 $this->errorLogger = $params['errorLogger'] ?? function ( Exception $e ) {
209 trigger_error( get_class( $e ) . ': ' . $e->getMessage(), E_USER_WARNING );
210 };
211 $this->deprecationLogger = $params['deprecationLogger'] ?? function ( $msg ) {
212 trigger_error( $msg, E_USER_DEPRECATED );
213 };
214
215 foreach ( [ 'replLogger', 'connLogger', 'queryLogger', 'perfLogger' ] as $key ) {
216 $this->$key = $params[$key] ?? new NullLogger();
217 }
218
219 $this->hostname = $params['hostname'] ?? ( gethostname() ?: 'unknown' );
220 $this->cliMode = $params['cliMode'] ?? ( PHP_SAPI === 'cli' || PHP_SAPI === 'phpdbg' );
221 $this->agent = $params['agent'] ?? '';
222
223 if ( isset( $params['chronologyCallback'] ) ) {
224 $this->chronologyCallback = $params['chronologyCallback'];
225 }
226
227 if ( isset( $params['roundStage'] ) ) {
228 if ( $params['roundStage'] === self::STAGE_POSTCOMMIT_CALLBACKS ) {
229 $this->trxRoundStage = self::ROUND_COMMIT_CALLBACKS;
230 } elseif ( $params['roundStage'] === self::STAGE_POSTROLLBACK_CALLBACKS ) {
231 $this->trxRoundStage = self::ROUND_ROLLBACK_CALLBACKS;
232 }
233 }
234
235 $group = $params['defaultGroup'] ?? self::GROUP_GENERIC;
236 $this->defaultGroup = isset( $this->groupLoads[$group] ) ? $group : self::GROUP_GENERIC;
237
238 static $nextId;
239 $this->id = $nextId = ( is_int( $nextId ) ? $nextId++ : mt_rand() );
240 $this->ownerId = $params['ownerId'] ?? null;
241 }
242
243 private static function newTrackedConnectionsArray() {
244 return [
245 // Connection were transaction rounds may be applied
246 self::KEY_LOCAL => [],
247 self::KEY_FOREIGN_INUSE => [],
248 self::KEY_FOREIGN_FREE => [],
249 // Auto-committing counterpart connections that ignore transaction rounds
250 self::KEY_LOCAL_NOROUND => [],
251 self::KEY_FOREIGN_INUSE_NOROUND => [],
252 self::KEY_FOREIGN_FREE_NOROUND => []
253 ];
254 }
255
256 public function getLocalDomainID() {
257 return $this->localDomain->getId();
258 }
259
260 public function resolveDomainID( $domain ) {
261 if ( $domain === $this->localDomainIdAlias || $domain === false ) {
262 // Local connection requested via some backwards-compatibility domain alias
263 return $this->getLocalDomainID();
264 }
265
266 return (string)$domain;
267 }
268
269 /**
270 * Resolve $groups into a list of query groups defining as having database servers
271 *
272 * @param string[]|string|bool $groups Query group(s) in preference order, [], or false
273 * @param int $i Specific server index or DB_MASTER/DB_REPLICA
274 * @return string[] Non-empty group list in preference order with the default group appended
275 */
276 private function resolveGroups( $groups, $i ) {
277 // If a specific replica server was specified, then $groups makes no sense
278 if ( $i > 0 && $groups !== [] && $groups !== false ) {
279 $list = implode( ', ', (array)$groups );
280 throw new LogicException( "Query group(s) ($list) given with server index (#$i)" );
281 }
282
283 if ( $groups === [] || $groups === false || $groups === $this->defaultGroup ) {
284 $resolvedGroups = [ $this->defaultGroup ]; // common case
285 } elseif ( is_string( $groups ) && isset( $this->groupLoads[$groups] ) ) {
286 $resolvedGroups = [ $groups, $this->defaultGroup ];
287 } elseif ( is_array( $groups ) ) {
288 $resolvedGroups = array_keys( array_flip( $groups ) + [ self::GROUP_GENERIC => 1 ] );
289 } else {
290 $resolvedGroups = [ $this->defaultGroup ];
291 }
292
293 return $resolvedGroups;
294 }
295
296 /**
297 * @param int $flags Bitfield of class CONN_* constants
298 * @param int $i Specific server index or DB_MASTER/DB_REPLICA
299 * @return int Sanitized bitfield
300 */
301 private function sanitizeConnectionFlags( $flags, $i ) {
302 // Whether an outside caller is explicitly requesting the master database server
303 if ( $i === self::DB_MASTER || $i === $this->getWriterIndex() ) {
304 $flags |= self::CONN_INTENT_WRITABLE;
305 }
306
307 if ( ( $flags & self::CONN_TRX_AUTOCOMMIT ) == self::CONN_TRX_AUTOCOMMIT ) {
308 // Callers use CONN_TRX_AUTOCOMMIT to bypass REPEATABLE-READ staleness without
309 // resorting to row locks (e.g. FOR UPDATE) or to make small out-of-band commits
310 // during larger transactions. This is useful for avoiding lock contention.
311
312 // Master DB server attributes (should match those of the replica DB servers)
313 $attributes = $this->getServerAttributes( $this->getWriterIndex() );
314 if ( $attributes[Database::ATTR_DB_LEVEL_LOCKING] ) {
315 // The RDBMS does not support concurrent writes (e.g. SQLite), so attempts
316 // to use separate connections would just cause self-deadlocks. Note that
317 // REPEATABLE-READ staleness is not an issue since DB-level locking means
318 // that transactions are Strict Serializable anyway.
319 $flags &= ~self::CONN_TRX_AUTOCOMMIT;
320 $type = $this->getServerType( $this->getWriterIndex() );
321 $this->connLogger->info( __METHOD__ . ": CONN_TRX_AUTOCOMMIT disallowed ($type)" );
322 }
323 }
324
325 return $flags;
326 }
327
328 /**
329 * @param IDatabase $conn
330 * @param int $flags
331 * @throws DBUnexpectedError
332 */
333 private function enforceConnectionFlags( IDatabase $conn, $flags ) {
334 if ( ( $flags & self::CONN_TRX_AUTOCOMMIT ) == self::CONN_TRX_AUTOCOMMIT ) {
335 if ( $conn->trxLevel() ) { // sanity
336 throw new DBUnexpectedError(
337 $conn,
338 'Handle requested with CONN_TRX_AUTOCOMMIT yet it has a transaction'
339 );
340 }
341
342 $conn->clearFlag( $conn::DBO_TRX ); // auto-commit mode
343 }
344 }
345
346 /**
347 * Get a LoadMonitor instance
348 *
349 * @return ILoadMonitor
350 */
351 private function getLoadMonitor() {
352 if ( !isset( $this->loadMonitor ) ) {
353 $compat = [
354 'LoadMonitor' => LoadMonitor::class,
355 'LoadMonitorNull' => LoadMonitorNull::class,
356 'LoadMonitorMySQL' => LoadMonitorMySQL::class,
357 ];
358
359 $class = $this->loadMonitorConfig['class'];
360 if ( isset( $compat[$class] ) ) {
361 $class = $compat[$class];
362 }
363
364 $this->loadMonitor = new $class(
365 $this, $this->srvCache, $this->wanCache, $this->loadMonitorConfig );
366 $this->loadMonitor->setLogger( $this->replLogger );
367 }
368
369 return $this->loadMonitor;
370 }
371
372 /**
373 * @param array $loads
374 * @param bool|string $domain Domain to get non-lagged for
375 * @param int $maxLag Restrict the maximum allowed lag to this many seconds
376 * @return bool|int|string
377 */
378 private function getRandomNonLagged( array $loads, $domain = false, $maxLag = INF ) {
379 $lags = $this->getLagTimes( $domain );
380
381 # Unset excessively lagged servers
382 foreach ( $lags as $i => $lag ) {
383 if ( $i !== $this->getWriterIndex() ) {
384 # How much lag this server nominally is allowed to have
385 $maxServerLag = $this->servers[$i]['max lag'] ?? $this->maxLag; // default
386 # Constrain that futher by $maxLag argument
387 $maxServerLag = min( $maxServerLag, $maxLag );
388
389 $host = $this->getServerName( $i );
390 if ( $lag === false && !is_infinite( $maxServerLag ) ) {
391 $this->replLogger->debug(
392 __METHOD__ .
393 ": server {host} is not replicating?", [ 'host' => $host ] );
394 unset( $loads[$i] );
395 } elseif ( $lag > $maxServerLag ) {
396 $this->replLogger->debug(
397 __METHOD__ .
398 ": server {host} has {lag} seconds of lag (>= {maxlag})",
399 [ 'host' => $host, 'lag' => $lag, 'maxlag' => $maxServerLag ]
400 );
401 unset( $loads[$i] );
402 }
403 }
404 }
405
406 # Find out if all the replica DBs with non-zero load are lagged
407 $sum = 0;
408 foreach ( $loads as $load ) {
409 $sum += $load;
410 }
411 if ( $sum == 0 ) {
412 # No appropriate DB servers except maybe the master and some replica DBs with zero load
413 # Do NOT use the master
414 # Instead, this function will return false, triggering read-only mode,
415 # and a lagged replica DB will be used instead.
416 return false;
417 }
418
419 if ( count( $loads ) == 0 ) {
420 return false;
421 }
422
423 # Return a random representative of the remainder
424 return ArrayUtils::pickRandom( $loads );
425 }
426
427 /**
428 * Get the server index to use for a specified server index and query group list
429 *
430 * @param int $i Specific server index or DB_MASTER/DB_REPLICA
431 * @param string[] $groups Non-empty query group list in preference order
432 * @param string|bool $domain
433 * @return int A specific server index (replica DBs are checked for connectivity)
434 */
435 private function getConnectionIndex( $i, array $groups, $domain ) {
436 if ( $i === self::DB_MASTER ) {
437 $i = $this->getWriterIndex();
438 } elseif ( $i === self::DB_REPLICA ) {
439 foreach ( $groups as $group ) {
440 $groupIndex = $this->getReaderIndex( $group, $domain );
441 if ( $groupIndex !== false ) {
442 $i = $groupIndex; // group connection succeeded
443 break;
444 }
445 }
446 } elseif ( !isset( $this->servers[$i] ) ) {
447 throw new UnexpectedValueException( "Invalid server index index #$i" );
448 }
449
450 if ( $i === self::DB_REPLICA ) {
451 $this->lastError = 'Unknown error'; // set here in case of worse failure
452 $this->lastError = 'No working replica DB server: ' . $this->lastError;
453 $this->reportConnectionError();
454 return null; // unreachable due to exception
455 }
456
457 return $i;
458 }
459
460 public function getReaderIndex( $group = false, $domain = false ) {
461 if ( $this->getServerCount() == 1 ) {
462 // Skip the load balancing if there's only one server
463 return $this->getWriterIndex();
464 }
465
466 $group = is_string( $group ) ? $group : self::GROUP_GENERIC;
467
468 $index = $this->getExistingReaderIndex( $group );
469 if ( $index >= 0 ) {
470 // A reader index was already selected and "waitForPos" was handled
471 return $index;
472 }
473
474 // Use the server weight array for this load group
475 if ( isset( $this->groupLoads[$group] ) ) {
476 $loads = $this->groupLoads[$group];
477 } else {
478 $this->connLogger->info( __METHOD__ . ": no loads for group $group" );
479
480 return false;
481 }
482
483 // Scale the configured load ratios according to each server's load and state
484 $this->getLoadMonitor()->scaleLoads( $loads, $domain );
485
486 // Pick a server to use, accounting for weights, load, lag, and "waitForPos"
487 $this->lazyLoadReplicationPositions(); // optimizes server candidate selection
488 list( $i, $laggedReplicaMode ) = $this->pickReaderIndex( $loads, $domain );
489 if ( $i === false ) {
490 // DB connection unsuccessful
491 return false;
492 }
493
494 // If data seen by queries is expected to reflect the transactions committed as of
495 // or after a given replication position then wait for the DB to apply those changes
496 if ( $this->waitForPos && $i !== $this->getWriterIndex() && !$this->doWait( $i ) ) {
497 // Data will be outdated compared to what was expected
498 $laggedReplicaMode = true;
499 }
500
501 // Cache the reader index for future DB_REPLICA handles
502 $this->setExistingReaderIndex( $group, $i );
503 // Record whether the generic reader index is in "lagged replica DB" mode
504 if ( $group === self::GROUP_GENERIC && $laggedReplicaMode ) {
505 $this->laggedReplicaMode = true;
506 }
507
508 $serverName = $this->getServerName( $i );
509 $this->connLogger->debug( __METHOD__ . ": using server $serverName for group '$group'" );
510
511 return $i;
512 }
513
514 /**
515 * Get the server index chosen by the load balancer for use with the given query group
516 *
517 * @param string $group Query group; use false for the generic group
518 * @return int Server index or -1 if none was chosen
519 */
520 protected function getExistingReaderIndex( $group ) {
521 return $this->readIndexByGroup[$group] ?? -1;
522 }
523
524 /**
525 * Set the server index chosen by the load balancer for use with the given query group
526 *
527 * @param string $group Query group; use false for the generic group
528 * @param int $index The index of a specific server
529 */
530 private function setExistingReaderIndex( $group, $index ) {
531 if ( $index < 0 ) {
532 throw new UnexpectedValueException( "Cannot set a negative read server index" );
533 }
534 $this->readIndexByGroup[$group] = $index;
535 }
536
537 /**
538 * @param array $loads List of server weights
539 * @param string|bool $domain
540 * @return array (reader index, lagged replica mode) or (false, false) on failure
541 */
542 private function pickReaderIndex( array $loads, $domain = false ) {
543 if ( $loads === [] ) {
544 throw new InvalidArgumentException( "Server configuration array is empty" );
545 }
546
547 /** @var int|bool $i Index of selected server */
548 $i = false;
549 /** @var bool $laggedReplicaMode Whether server is considered lagged */
550 $laggedReplicaMode = false;
551
552 // Quickly look through the available servers for a server that meets criteria...
553 $currentLoads = $loads;
554 while ( count( $currentLoads ) ) {
555 if ( $this->allowLagged || $laggedReplicaMode ) {
556 $i = ArrayUtils::pickRandom( $currentLoads );
557 } else {
558 $i = false;
559 if ( $this->waitForPos && $this->waitForPos->asOfTime() ) {
560 $this->replLogger->debug( __METHOD__ . ": replication positions detected" );
561 // "chronologyCallback" sets "waitForPos" for session consistency.
562 // This triggers doWait() after connect, so it's especially good to
563 // avoid lagged servers so as to avoid excessive delay in that method.
564 $ago = microtime( true ) - $this->waitForPos->asOfTime();
565 // Aim for <= 1 second of waiting (being too picky can backfire)
566 $i = $this->getRandomNonLagged( $currentLoads, $domain, $ago + 1 );
567 }
568 if ( $i === false ) {
569 // Any server with less lag than it's 'max lag' param is preferable
570 $i = $this->getRandomNonLagged( $currentLoads, $domain );
571 }
572 if ( $i === false && count( $currentLoads ) ) {
573 // All replica DBs lagged. Switch to read-only mode
574 $this->replLogger->error(
575 __METHOD__ . ": all replica DBs lagged. Switch to read-only mode" );
576 $i = ArrayUtils::pickRandom( $currentLoads );
577 $laggedReplicaMode = true;
578 }
579 }
580
581 if ( $i === false ) {
582 // pickRandom() returned false.
583 // This is permanent and means the configuration or the load monitor
584 // wants us to return false.
585 $this->connLogger->debug( __METHOD__ . ": pickRandom() returned false" );
586
587 return [ false, false ];
588 }
589
590 $serverName = $this->getServerName( $i );
591 $this->connLogger->debug( __METHOD__ . ": Using reader #$i: $serverName..." );
592
593 // Get a connection to this server without triggering other server connections
594 $conn = $this->getServerConnection( $i, $domain, self::CONN_SILENCE_ERRORS );
595 if ( !$conn ) {
596 $this->connLogger->warning( __METHOD__ . ": Failed connecting to $i/$domain" );
597 unset( $currentLoads[$i] ); // avoid this server next iteration
598 $i = false;
599 continue;
600 }
601
602 // Decrement reference counter, we are finished with this connection.
603 // It will be incremented for the caller later.
604 if ( $domain !== false ) {
605 $this->reuseConnection( $conn );
606 }
607
608 // Return this server
609 break;
610 }
611
612 // If all servers were down, quit now
613 if ( $currentLoads === [] ) {
614 $this->connLogger->error( __METHOD__ . ": all servers down" );
615 }
616
617 return [ $i, $laggedReplicaMode ];
618 }
619
620 public function waitFor( $pos ) {
621 $oldPos = $this->waitForPos;
622 try {
623 $this->waitForPos = $pos;
624 // If a generic reader connection was already established, then wait now
625 $i = $this->getExistingReaderIndex( self::GROUP_GENERIC );
626 if ( $i > 0 && !$this->doWait( $i ) ) {
627 $this->laggedReplicaMode = true;
628 }
629 // Otherwise, wait until a connection is established in getReaderIndex()
630 } finally {
631 // Restore the older position if it was higher since this is used for lag-protection
632 $this->setWaitForPositionIfHigher( $oldPos );
633 }
634 }
635
636 public function waitForOne( $pos, $timeout = null ) {
637 $oldPos = $this->waitForPos;
638 try {
639 $this->waitForPos = $pos;
640
641 $i = $this->getExistingReaderIndex( self::GROUP_GENERIC );
642 if ( $i <= 0 ) {
643 // Pick a generic replica DB if there isn't one yet
644 $readLoads = $this->groupLoads[self::GROUP_GENERIC];
645 unset( $readLoads[$this->getWriterIndex()] ); // replica DBs only
646 $readLoads = array_filter( $readLoads ); // with non-zero load
647 $i = ArrayUtils::pickRandom( $readLoads );
648 }
649
650 if ( $i > 0 ) {
651 $ok = $this->doWait( $i, true, $timeout );
652 } else {
653 $ok = true; // no applicable loads
654 }
655 } finally {
656 // Restore the old position; this is used for throttling, not lag-protection
657 $this->waitForPos = $oldPos;
658 }
659
660 return $ok;
661 }
662
663 public function waitForAll( $pos, $timeout = null ) {
664 $timeout = $timeout ?: $this->waitTimeout;
665
666 $oldPos = $this->waitForPos;
667 try {
668 $this->waitForPos = $pos;
669 $serverCount = $this->getServerCount();
670
671 $ok = true;
672 for ( $i = 1; $i < $serverCount; $i++ ) {
673 if ( $this->serverHasLoadInAnyGroup( $i ) ) {
674 $start = microtime( true );
675 $ok = $this->doWait( $i, true, $timeout ) && $ok;
676 $timeout -= intval( microtime( true ) - $start );
677 if ( $timeout <= 0 ) {
678 break; // timeout reached
679 }
680 }
681 }
682 } finally {
683 // Restore the old position; this is used for throttling, not lag-protection
684 $this->waitForPos = $oldPos;
685 }
686
687 return $ok;
688 }
689
690 /**
691 * @param int $i Specific server index
692 * @return bool
693 */
694 private function serverHasLoadInAnyGroup( $i ) {
695 foreach ( $this->groupLoads as $loadsByIndex ) {
696 if ( ( $loadsByIndex[$i] ?? 0 ) > 0 ) {
697 return true;
698 }
699 }
700
701 return false;
702 }
703
704 /**
705 * @param DBMasterPos|bool $pos
706 */
707 private function setWaitForPositionIfHigher( $pos ) {
708 if ( !$pos ) {
709 return;
710 }
711
712 if ( !$this->waitForPos || $pos->hasReached( $this->waitForPos ) ) {
713 $this->waitForPos = $pos;
714 }
715 }
716
717 public function getAnyOpenConnection( $i, $flags = 0 ) {
718 $i = ( $i === self::DB_MASTER ) ? $this->getWriterIndex() : $i;
719 // Connection handles required to be in auto-commit mode use a separate connection
720 // pool since the main pool is effected by implicit and explicit transaction rounds
721 $autocommit = ( ( $flags & self::CONN_TRX_AUTOCOMMIT ) == self::CONN_TRX_AUTOCOMMIT );
722
723 $conn = false;
724 foreach ( $this->conns as $connsByServer ) {
725 // Get the connection array server indexes to inspect
726 if ( $i === self::DB_REPLICA ) {
727 $indexes = array_keys( $connsByServer );
728 } else {
729 $indexes = isset( $connsByServer[$i] ) ? [ $i ] : [];
730 }
731
732 foreach ( $indexes as $index ) {
733 $conn = $this->pickAnyOpenConnection( $connsByServer[$index], $autocommit );
734 if ( $conn ) {
735 break;
736 }
737 }
738 }
739
740 if ( $conn ) {
741 $this->enforceConnectionFlags( $conn, $flags );
742 }
743
744 return $conn;
745 }
746
747 /**
748 * @param IDatabase[] $candidateConns
749 * @param bool $autocommit Whether to only look for auto-commit connections
750 * @return IDatabase|false An appropriate open connection or false if none found
751 */
752 private function pickAnyOpenConnection( $candidateConns, $autocommit ) {
753 $conn = false;
754
755 foreach ( $candidateConns as $candidateConn ) {
756 if ( !$candidateConn->isOpen() ) {
757 continue; // some sort of error occured?
758 } elseif (
759 $autocommit &&
760 (
761 // Connection is transaction round aware
762 !$candidateConn->getLBInfo( 'autoCommitOnly' ) ||
763 // Some sort of error left a transaction open?
764 $candidateConn->trxLevel()
765 )
766 ) {
767 continue; // some sort of error left a transaction open?
768 }
769
770 $conn = $candidateConn;
771 }
772
773 return $conn;
774 }
775
776 /**
777 * Wait for a given replica DB to catch up to the master pos stored in "waitForPos"
778 * @param int $index Specific server index
779 * @param bool $open Check the server even if a new connection has to be made
780 * @param int|null $timeout Max seconds to wait; default is "waitTimeout"
781 * @return bool
782 */
783 protected function doWait( $index, $open = false, $timeout = null ) {
784 $timeout = max( 1, intval( $timeout ?: $this->waitTimeout ) );
785
786 // Check if we already know that the DB has reached this point
787 $server = $this->getServerName( $index );
788 $key = $this->srvCache->makeGlobalKey( __CLASS__, 'last-known-pos', $server, 'v1' );
789 /** @var DBMasterPos $knownReachedPos */
790 $knownReachedPos = $this->srvCache->get( $key );
791 if (
792 $knownReachedPos instanceof DBMasterPos &&
793 $knownReachedPos->hasReached( $this->waitForPos )
794 ) {
795 $this->replLogger->debug(
796 __METHOD__ .
797 ': replica DB {dbserver} known to be caught up (pos >= $knownReachedPos).',
798 [ 'dbserver' => $server ]
799 );
800 return true;
801 }
802
803 // Find a connection to wait on, creating one if needed and allowed
804 $close = false; // close the connection afterwards
805 $flags = self::CONN_SILENCE_ERRORS;
806 $conn = $this->getAnyOpenConnection( $index, $flags );
807 if ( !$conn ) {
808 if ( !$open ) {
809 $this->replLogger->debug(
810 __METHOD__ . ': no connection open for {dbserver}',
811 [ 'dbserver' => $server ]
812 );
813
814 return false;
815 }
816 // Get a connection to this server without triggering other server connections
817 $conn = $this->getServerConnection( $index, self::DOMAIN_ANY, $flags );
818 if ( !$conn ) {
819 $this->replLogger->warning(
820 __METHOD__ . ': failed to connect to {dbserver}',
821 [ 'dbserver' => $server ]
822 );
823
824 return false;
825 }
826 // Avoid connection spam in waitForAll() when connections
827 // are made just for the sake of doing this lag check.
828 $close = true;
829 }
830
831 $this->replLogger->info(
832 __METHOD__ .
833 ': waiting for replica DB {dbserver} to catch up...',
834 [ 'dbserver' => $server ]
835 );
836
837 $result = $conn->masterPosWait( $this->waitForPos, $timeout );
838
839 if ( $result === null ) {
840 $this->replLogger->warning(
841 __METHOD__ . ': Errored out waiting on {host} pos {pos}',
842 [
843 'host' => $server,
844 'pos' => $this->waitForPos,
845 'trace' => ( new RuntimeException() )->getTraceAsString()
846 ]
847 );
848 $ok = false;
849 } elseif ( $result == -1 ) {
850 $this->replLogger->warning(
851 __METHOD__ . ': Timed out waiting on {host} pos {pos}',
852 [
853 'host' => $server,
854 'pos' => $this->waitForPos,
855 'trace' => ( new RuntimeException() )->getTraceAsString()
856 ]
857 );
858 $ok = false;
859 } else {
860 $this->replLogger->debug( __METHOD__ . ": done waiting" );
861 $ok = true;
862 // Remember that the DB reached this point
863 $this->srvCache->set( $key, $this->waitForPos, BagOStuff::TTL_DAY );
864 }
865
866 if ( $close ) {
867 $this->closeConnection( $conn );
868 }
869
870 return $ok;
871 }
872
873 public function getConnection( $i, $groups = [], $domain = false, $flags = 0 ) {
874 $domain = $this->resolveDomainID( $domain );
875 $groups = $this->resolveGroups( $groups, $i );
876 $flags = $this->sanitizeConnectionFlags( $flags, $i );
877 // If given DB_MASTER/DB_REPLICA, resolve it to a specific server index. Resolving
878 // DB_REPLICA might trigger getServerConnection() calls due to the getReaderIndex()
879 // connectivity checks or LoadMonitor::scaleLoads() server state cache regeneration.
880 // The use of getServerConnection() instead of getConnection() avoids infinite loops.
881 $serverIndex = $this->getConnectionIndex( $i, $groups, $domain );
882 // Get an open connection to that server (might trigger a new connection)
883 $conn = $this->getServerConnection( $serverIndex, $domain, $flags );
884 // Set master DB handles as read-only if there is high replication lag
885 if ( $serverIndex === $this->getWriterIndex() && $this->getLaggedReplicaMode( $domain ) ) {
886 $reason = ( $this->getExistingReaderIndex( self::GROUP_GENERIC ) >= 0 )
887 ? 'The database is read-only until replication lag decreases.'
888 : 'The database is read-only until replica database servers becomes reachable.';
889 $conn->setLBInfo( 'readOnlyReason', $reason );
890 }
891
892 return $conn;
893 }
894
895 /**
896 * @param int $i Specific server index
897 * @param string $domain Resolved DB domain
898 * @param int $flags Bitfield of class CONN_* constants
899 * @return IDatabase|bool
900 * @throws InvalidArgumentException When the server index is invalid
901 */
902 public function getServerConnection( $i, $domain, $flags = 0 ) {
903 // Number of connections made before getting the server index and handle
904 $priorConnectionsMade = $this->connectionCounter;
905 // Get an open connection to this server (might trigger a new connection)
906 $conn = $this->localDomain->equals( $domain )
907 ? $this->getLocalConnection( $i, $flags )
908 : $this->getForeignConnection( $i, $domain, $flags );
909 // Throw an error or otherwise bail out if the connection attempt failed
910 if ( !( $conn instanceof IDatabase ) ) {
911 if ( ( $flags & self::CONN_SILENCE_ERRORS ) != self::CONN_SILENCE_ERRORS ) {
912 $this->reportConnectionError();
913 }
914
915 return false;
916 }
917
918 // Profile any new connections caused by this method
919 if ( $this->connectionCounter > $priorConnectionsMade ) {
920 $this->trxProfiler->recordConnection(
921 $conn->getServer(),
922 $conn->getDBname(),
923 ( ( $flags & self::CONN_INTENT_WRITABLE ) == self::CONN_INTENT_WRITABLE )
924 );
925 }
926
927 if ( !$conn->isOpen() ) {
928 $this->errorConnection = $conn;
929 // Connection was made but later unrecoverably lost for some reason.
930 // Do not return a handle that will just throw exceptions on use, but
931 // let the calling code, e.g. getReaderIndex(), try another server.
932 return false;
933 }
934
935 // Make sure that flags like CONN_TRX_AUTOCOMMIT are respected by this handle
936 $this->enforceConnectionFlags( $conn, $flags );
937 // Set master DB handles as read-only if the load balancer is configured as read-only
938 // or the master database server is running in server-side read-only mode. Note that
939 // replica DB handles are always read-only via Database::assertIsWritableMaster().
940 // Read-only mode due to replication lag is *avoided* here to avoid recursion.
941 if ( $conn->getLBInfo( 'serverIndex' ) === $this->getWriterIndex() ) {
942 if ( $this->readOnlyReason !== false ) {
943 $conn->setLBInfo( 'readOnlyReason', $this->readOnlyReason );
944 } elseif ( $this->masterRunningReadOnly( $domain, $conn ) ) {
945 $conn->setLBInfo(
946 'readOnlyReason',
947 'The master database server is running in read-only mode.'
948 );
949 }
950 }
951
952 return $conn;
953 }
954
955 public function reuseConnection( IDatabase $conn ) {
956 $serverIndex = $conn->getLBInfo( 'serverIndex' );
957 $refCount = $conn->getLBInfo( 'foreignPoolRefCount' );
958 if ( $serverIndex === null || $refCount === null ) {
959 return; // non-foreign connection; no domain-use tracking to update
960 } elseif ( $conn instanceof DBConnRef ) {
961 // DBConnRef already handles calling reuseConnection() and only passes the live
962 // Database instance to this method. Any caller passing in a DBConnRef is broken.
963 $this->connLogger->error(
964 __METHOD__ . ": got DBConnRef instance.\n" .
965 ( new LogicException() )->getTraceAsString() );
966
967 return;
968 }
969
970 if ( $this->disabled ) {
971 return; // DBConnRef handle probably survived longer than the LoadBalancer
972 }
973
974 if ( $conn->getLBInfo( 'autoCommitOnly' ) ) {
975 $connFreeKey = self::KEY_FOREIGN_FREE_NOROUND;
976 $connInUseKey = self::KEY_FOREIGN_INUSE_NOROUND;
977 } else {
978 $connFreeKey = self::KEY_FOREIGN_FREE;
979 $connInUseKey = self::KEY_FOREIGN_INUSE;
980 }
981
982 $domain = $conn->getDomainID();
983 if ( !isset( $this->conns[$connInUseKey][$serverIndex][$domain] ) ) {
984 throw new InvalidArgumentException(
985 "Connection $serverIndex/$domain not found; it may have already been freed" );
986 } elseif ( $this->conns[$connInUseKey][$serverIndex][$domain] !== $conn ) {
987 throw new InvalidArgumentException(
988 "Connection $serverIndex/$domain mismatched; it may have already been freed" );
989 }
990
991 $conn->setLBInfo( 'foreignPoolRefCount', --$refCount );
992 if ( $refCount <= 0 ) {
993 $this->conns[$connFreeKey][$serverIndex][$domain] = $conn;
994 unset( $this->conns[$connInUseKey][$serverIndex][$domain] );
995 if ( !$this->conns[$connInUseKey][$serverIndex] ) {
996 unset( $this->conns[$connInUseKey][$serverIndex] ); // clean up
997 }
998 $this->connLogger->debug( __METHOD__ . ": freed connection $serverIndex/$domain" );
999 } else {
1000 $this->connLogger->debug( __METHOD__ .
1001 ": reference count for $serverIndex/$domain reduced to $refCount" );
1002 }
1003 }
1004
1005 public function getConnectionRef( $i, $groups = [], $domain = false, $flags = 0 ) {
1006 $domain = $this->resolveDomainID( $domain );
1007 $role = $this->getRoleFromIndex( $i );
1008
1009 return new DBConnRef( $this, $this->getConnection( $i, $groups, $domain, $flags ), $role );
1010 }
1011
1012 public function getLazyConnectionRef( $i, $groups = [], $domain = false, $flags = 0 ) {
1013 $domain = $this->resolveDomainID( $domain );
1014 $role = $this->getRoleFromIndex( $i );
1015
1016 return new DBConnRef( $this, [ $i, $groups, $domain, $flags ], $role );
1017 }
1018
1019 public function getMaintenanceConnectionRef( $i, $groups = [], $domain = false, $flags = 0 ) {
1020 $domain = $this->resolveDomainID( $domain );
1021 $role = $this->getRoleFromIndex( $i );
1022
1023 return new MaintainableDBConnRef(
1024 $this, $this->getConnection( $i, $groups, $domain, $flags ), $role );
1025 }
1026
1027 /**
1028 * @param int $i Server index or DB_MASTER/DB_REPLICA
1029 * @return int One of DB_MASTER/DB_REPLICA
1030 */
1031 private function getRoleFromIndex( $i ) {
1032 return ( $i === self::DB_MASTER || $i === $this->getWriterIndex() )
1033 ? self::DB_MASTER
1034 : self::DB_REPLICA;
1035 }
1036
1037 /**
1038 * @param int $i
1039 * @param string|bool $domain
1040 * @param int $flags
1041 * @return Database|bool Live database handle or false on failure
1042 * @deprecated Since 1.34 Use getConnection() instead
1043 */
1044 public function openConnection( $i, $domain = false, $flags = 0 ) {
1045 return $this->getConnection( $i, [], $domain, $flags | self::CONN_SILENCE_ERRORS );
1046 }
1047
1048 /**
1049 * Open a connection to a local DB, or return one if it is already open.
1050 *
1051 * On error, returns false, and the connection which caused the
1052 * error will be available via $this->errorConnection.
1053 *
1054 * @note If disable() was called on this LoadBalancer, this method will throw a DBAccessError.
1055 *
1056 * @param int $i Specific server index
1057 * @param int $flags Class CONN_* constant bitfield
1058 * @return Database
1059 * @throws InvalidArgumentException When the server index is invalid
1060 * @throws UnexpectedValueException When the DB domain of the connection is corrupted
1061 */
1062 private function getLocalConnection( $i, $flags = 0 ) {
1063 $autoCommit = ( ( $flags & self::CONN_TRX_AUTOCOMMIT ) == self::CONN_TRX_AUTOCOMMIT );
1064 // Connection handles required to be in auto-commit mode use a separate connection
1065 // pool since the main pool is effected by implicit and explicit transaction rounds
1066 $connKey = $autoCommit ? self::KEY_LOCAL_NOROUND : self::KEY_LOCAL;
1067
1068 if ( isset( $this->conns[$connKey][$i][0] ) ) {
1069 $conn = $this->conns[$connKey][$i][0];
1070 } else {
1071 $conn = $this->reallyOpenConnection(
1072 $i,
1073 $this->localDomain,
1074 [ 'autoCommitOnly' => $autoCommit ]
1075 );
1076 if ( $conn->isOpen() ) {
1077 $this->connLogger->debug( __METHOD__ . ": opened new connection for $i" );
1078 $this->conns[$connKey][$i][0] = $conn;
1079 } else {
1080 $this->connLogger->warning( __METHOD__ . ": connection error for $i" );
1081 $this->errorConnection = $conn;
1082 $conn = false;
1083 }
1084 }
1085
1086 // Sanity check to make sure that the right domain is selected
1087 if (
1088 $conn instanceof IDatabase &&
1089 !$this->localDomain->isCompatible( $conn->getDomainID() )
1090 ) {
1091 throw new UnexpectedValueException(
1092 "Got connection to '{$conn->getDomainID()}', " .
1093 "but expected local domain ('{$this->localDomain}')"
1094 );
1095 }
1096
1097 return $conn;
1098 }
1099
1100 /**
1101 * Open a connection to a foreign DB, or return one if it is already open.
1102 *
1103 * Increments a reference count on the returned connection which locks the
1104 * connection to the requested domain. This reference count can be
1105 * decremented by calling reuseConnection().
1106 *
1107 * If a connection is open to the appropriate server already, but with the wrong
1108 * database, it will be switched to the right database and returned, as long as
1109 * it has been freed first with reuseConnection().
1110 *
1111 * On error, returns false, and the connection which caused the
1112 * error will be available via $this->errorConnection.
1113 *
1114 * @note If disable() was called on this LoadBalancer, this method will throw a DBAccessError.
1115 *
1116 * @param int $i Specific server index
1117 * @param string $domain Domain ID to open
1118 * @param int $flags Class CONN_* constant bitfield
1119 * @return Database|bool Returns false on connection error
1120 * @throws DBError When database selection fails
1121 * @throws InvalidArgumentException When the server index is invalid
1122 * @throws UnexpectedValueException When the DB domain of the connection is corrupted
1123 */
1124 private function getForeignConnection( $i, $domain, $flags = 0 ) {
1125 $domainInstance = DatabaseDomain::newFromId( $domain );
1126 $autoCommit = ( ( $flags & self::CONN_TRX_AUTOCOMMIT ) == self::CONN_TRX_AUTOCOMMIT );
1127 // Connection handles required to be in auto-commit mode use a separate connection
1128 // pool since the main pool is effected by implicit and explicit transaction rounds
1129 if ( $autoCommit ) {
1130 $connFreeKey = self::KEY_FOREIGN_FREE_NOROUND;
1131 $connInUseKey = self::KEY_FOREIGN_INUSE_NOROUND;
1132 } else {
1133 $connFreeKey = self::KEY_FOREIGN_FREE;
1134 $connInUseKey = self::KEY_FOREIGN_INUSE;
1135 }
1136
1137 /** @var Database $conn */
1138 $conn = null;
1139
1140 if ( isset( $this->conns[$connInUseKey][$i][$domain] ) ) {
1141 // Reuse an in-use connection for the same domain
1142 $conn = $this->conns[$connInUseKey][$i][$domain];
1143 $this->connLogger->debug( __METHOD__ . ": reusing connection $i/$domain" );
1144 } elseif ( isset( $this->conns[$connFreeKey][$i][$domain] ) ) {
1145 // Reuse a free connection for the same domain
1146 $conn = $this->conns[$connFreeKey][$i][$domain];
1147 unset( $this->conns[$connFreeKey][$i][$domain] );
1148 $this->conns[$connInUseKey][$i][$domain] = $conn;
1149 $this->connLogger->debug( __METHOD__ . ": reusing free connection $i/$domain" );
1150 } elseif ( !empty( $this->conns[$connFreeKey][$i] ) ) {
1151 // Reuse a free connection from another domain if possible
1152 foreach ( $this->conns[$connFreeKey][$i] as $oldDomain => $conn ) {
1153 if ( $domainInstance->getDatabase() !== null ) {
1154 // Check if changing the database will require a new connection.
1155 // In that case, leave the connection handle alone and keep looking.
1156 // This prevents connections from being closed mid-transaction and can
1157 // also avoid overhead if the same database will later be requested.
1158 if (
1159 $conn->databasesAreIndependent() &&
1160 $conn->getDBname() !== $domainInstance->getDatabase()
1161 ) {
1162 continue;
1163 }
1164 // Select the new database, schema, and prefix
1165 $conn->selectDomain( $domainInstance );
1166 } else {
1167 // Stay on the current database, but update the schema/prefix
1168 $conn->dbSchema( $domainInstance->getSchema() );
1169 $conn->tablePrefix( $domainInstance->getTablePrefix() );
1170 }
1171 unset( $this->conns[$connFreeKey][$i][$oldDomain] );
1172 // Note that if $domain is an empty string, getDomainID() might not match it
1173 $this->conns[$connInUseKey][$i][$conn->getDomainID()] = $conn;
1174 $this->connLogger->debug( __METHOD__ .
1175 ": reusing free connection from $oldDomain for $domain" );
1176 break;
1177 }
1178 }
1179
1180 if ( !$conn ) {
1181 $conn = $this->reallyOpenConnection(
1182 $i,
1183 $domainInstance,
1184 [
1185 'autoCommitOnly' => $autoCommit,
1186 'foreign' => true,
1187 'foreignPoolRefCount' => 0
1188 ]
1189 );
1190 if ( $conn->isOpen() ) {
1191 // Note that if $domain is an empty string, getDomainID() might not match it
1192 $this->conns[$connInUseKey][$i][$conn->getDomainID()] = $conn;
1193 $this->connLogger->debug( __METHOD__ . ": opened new connection for $i/$domain" );
1194 } else {
1195 $this->connLogger->warning( __METHOD__ . ": connection error for $i/$domain" );
1196 $this->errorConnection = $conn;
1197 $conn = false;
1198 }
1199 }
1200
1201 if ( $conn instanceof IDatabase ) {
1202 // Sanity check to make sure that the right domain is selected
1203 if ( !$domainInstance->isCompatible( $conn->getDomainID() ) ) {
1204 throw new UnexpectedValueException(
1205 "Got connection to '{$conn->getDomainID()}', but expected '$domain'" );
1206 }
1207 // Increment reference count
1208 $refCount = $conn->getLBInfo( 'foreignPoolRefCount' );
1209 $conn->setLBInfo( 'foreignPoolRefCount', $refCount + 1 );
1210 }
1211
1212 return $conn;
1213 }
1214
1215 public function getServerAttributes( $i ) {
1216 return Database::attributesFromType(
1217 $this->getServerType( $i ),
1218 $this->servers[$i]['driver'] ?? null
1219 );
1220 }
1221
1222 /**
1223 * Test if the specified index represents an open connection
1224 *
1225 * @param int $index Server index
1226 * @return bool
1227 */
1228 private function isOpen( $index ) {
1229 return (bool)$this->getAnyOpenConnection( $index );
1230 }
1231
1232 /**
1233 * Open a new network connection to a server (uncached)
1234 *
1235 * Returns a Database object whether or not the connection was successful.
1236 *
1237 * @param int $i Specific server index
1238 * @param DatabaseDomain $domain Domain the connection is for, possibly unspecified
1239 * @param array $lbInfo Additional information for setLBInfo()
1240 * @return Database
1241 * @throws DBAccessError
1242 * @throws InvalidArgumentException
1243 */
1244 protected function reallyOpenConnection( $i, DatabaseDomain $domain, array $lbInfo ) {
1245 if ( $this->disabled ) {
1246 throw new DBAccessError();
1247 }
1248
1249 $server = $this->getServerInfoStrict( $i );
1250 $server = array_merge( $server, [
1251 // Use the database specified in $domain (null means "none or entrypoint DB");
1252 // fallback to the $server default if the RDBMs is an embedded library using a file
1253 // on disk since there would be nothing to access to without a DB/file name.
1254 'dbname' => $this->getServerAttributes( $i )[Database::ATTR_DB_IS_FILE]
1255 ? ( $domain->getDatabase() ?? $server['dbname'] ?? null )
1256 : $domain->getDatabase(),
1257 // Override the $server default schema with that of $domain if specified
1258 'schema' => $domain->getSchema() ?? $server['schema'] ?? null,
1259 // Use the table prefix specified in $domain
1260 'tablePrefix' => $domain->getTablePrefix(),
1261 // Participate in transaction rounds if $server does not specify otherwise
1262 'flags' => $server['flags'] ?? IDatabase::DBO_DEFAULT,
1263 // Inject the PHP execution mode and the agent string
1264 'cliMode' => $this->cliMode,
1265 'agent' => $this->agent,
1266 // Inject object and callback dependencies
1267 'srvCache' => $this->srvCache,
1268 'connLogger' => $this->connLogger,
1269 'queryLogger' => $this->queryLogger,
1270 'errorLogger' => $this->errorLogger,
1271 'deprecationLogger' => $this->deprecationLogger,
1272 'profiler' => $this->profiler,
1273 'trxProfiler' => $this->trxProfiler
1274 ] );
1275
1276 $lbInfo = array_merge( $lbInfo, [
1277 'ownerId' => $this->id,
1278 'serverIndex' => $i,
1279 'master' => ( $i === $this->getWriterIndex() ),
1280 'replica' => ( $i !== $this->getWriterIndex() ),
1281 // Name of the master server of the relevant DB cluster (e.g. "db1052")
1282 'clusterMasterHost' => $this->getServerName( $this->getWriterIndex() )
1283 ] );
1284
1285 $conn = Database::factory( $server['type'], $server, Database::NEW_UNCONNECTED );
1286 try {
1287 $conn->initConnection();
1288 ++$this->connectionCounter;
1289 } catch ( DBConnectionError $e ) {
1290 // ignore; let the DB handle the logging
1291 }
1292
1293 $conn->setLBInfo( $lbInfo );
1294 if ( $conn->getFlag( $conn::DBO_DEFAULT ) ) {
1295 if ( $this->cliMode ) {
1296 $conn->clearFlag( $conn::DBO_TRX );
1297 } else {
1298 $conn->setFlag( $conn::DBO_TRX );
1299 }
1300 }
1301 if ( $i === $this->getWriterIndex() ) {
1302 if ( $this->trxRoundId !== false ) {
1303 $this->applyTransactionRoundFlags( $conn );
1304 }
1305 foreach ( $this->trxRecurringCallbacks as $name => $callback ) {
1306 $conn->setTransactionListener( $name, $callback );
1307 }
1308 }
1309 $conn->setTableAliases( $this->tableAliases );
1310 $conn->setIndexAliases( $this->indexAliases );
1311
1312 $conn->setLazyMasterHandle(
1313 $this->getLazyConnectionRef( self::DB_MASTER, [], $conn->getDomainID() )
1314 );
1315
1316 $this->lazyLoadReplicationPositions(); // session consistency
1317
1318 // Log when many connection are made on requests
1319 $count = $this->getCurrentConnectionCount();
1320 if ( $count >= self::CONN_HELD_WARN_THRESHOLD ) {
1321 $this->perfLogger->warning(
1322 __METHOD__ . ": {connections}+ connections made (master={masterdb})",
1323 [
1324 'connections' => $count,
1325 'dbserver' => $conn->getServer(),
1326 'masterdb' => $conn->getLBInfo( 'clusterMasterHost' )
1327 ]
1328 );
1329 }
1330
1331 return $conn;
1332 }
1333
1334 /**
1335 * Make sure that any "waitForPos" positions are loaded and available to doWait()
1336 */
1337 private function lazyLoadReplicationPositions() {
1338 if ( !$this->connectionAttempted && $this->chronologyCallback ) {
1339 $this->connectionAttempted = true;
1340 ( $this->chronologyCallback )( $this ); // generally calls waitFor()
1341 $this->connLogger->debug( __METHOD__ . ': executed chronology callback.' );
1342 }
1343 }
1344
1345 /**
1346 * @throws DBConnectionError
1347 */
1348 private function reportConnectionError() {
1349 $conn = $this->errorConnection; // the connection which caused the error
1350 $context = [
1351 'method' => __METHOD__,
1352 'last_error' => $this->lastError,
1353 ];
1354
1355 if ( $conn instanceof IDatabase ) {
1356 $context['db_server'] = $conn->getServer();
1357 $this->connLogger->warning(
1358 __METHOD__ . ": connection error: {last_error} ({db_server})",
1359 $context
1360 );
1361
1362 throw new DBConnectionError( $conn, "{$this->lastError} ({$context['db_server']})" );
1363 } else {
1364 // No last connection, probably due to all servers being too busy
1365 $this->connLogger->error(
1366 __METHOD__ .
1367 ": LB failure with no last connection. Connection error: {last_error}",
1368 $context
1369 );
1370
1371 // If all servers were busy, "lastError" will contain something sensible
1372 throw new DBConnectionError( null, $this->lastError );
1373 }
1374 }
1375
1376 public function getWriterIndex() {
1377 return 0;
1378 }
1379
1380 /**
1381 * Returns true if the specified index is a valid server index
1382 *
1383 * @param int $i
1384 * @return bool
1385 * @deprecated Since 1.34
1386 */
1387 public function haveIndex( $i ) {
1388 return array_key_exists( $i, $this->servers );
1389 }
1390
1391 /**
1392 * Returns true if the specified index is valid and has non-zero load
1393 *
1394 * @param int $i
1395 * @return bool
1396 * @deprecated Since 1.34
1397 */
1398 public function isNonZeroLoad( $i ) {
1399 return ( isset( $this->servers[$i] ) && $this->groupLoads[self::GROUP_GENERIC][$i] > 0 );
1400 }
1401
1402 public function getServerCount() {
1403 return count( $this->servers );
1404 }
1405
1406 public function hasReplicaServers() {
1407 return ( $this->getServerCount() > 1 );
1408 }
1409
1410 public function hasStreamingReplicaServers() {
1411 foreach ( $this->servers as $i => $server ) {
1412 if ( $i !== $this->getWriterIndex() && empty( $server['is static'] ) ) {
1413 return true;
1414 }
1415 }
1416
1417 return false;
1418 }
1419
1420 public function getServerName( $i ) {
1421 $name = $this->servers[$i]['hostName'] ?? ( $this->servers[$i]['host'] ?? '' );
1422
1423 return ( $name != '' ) ? $name : 'localhost';
1424 }
1425
1426 public function getServerInfo( $i ) {
1427 return $this->servers[$i] ?? false;
1428 }
1429
1430 public function getServerType( $i ) {
1431 return $this->servers[$i]['type'] ?? 'unknown';
1432 }
1433
1434 public function getMasterPos() {
1435 $index = $this->getWriterIndex();
1436
1437 $conn = $this->getAnyOpenConnection( $index );
1438 if ( $conn ) {
1439 return $conn->getMasterPos();
1440 }
1441
1442 $conn = $this->getConnection( $index, self::CONN_SILENCE_ERRORS );
1443 if ( !$conn ) {
1444 $this->reportConnectionError();
1445 return null; // unreachable due to exception
1446 }
1447
1448 try {
1449 $pos = $conn->getMasterPos();
1450 } finally {
1451 $this->closeConnection( $conn );
1452 }
1453
1454 return $pos;
1455 }
1456
1457 public function getReplicaResumePos() {
1458 // Get the position of any existing master server connection
1459 $masterConn = $this->getAnyOpenConnection( $this->getWriterIndex() );
1460 if ( $masterConn ) {
1461 return $masterConn->getMasterPos();
1462 }
1463
1464 // Get the highest position of any existing replica server connection
1465 $highestPos = false;
1466 $serverCount = $this->getServerCount();
1467 for ( $i = 1; $i < $serverCount; $i++ ) {
1468 if ( !empty( $this->servers[$i]['is static'] ) ) {
1469 continue; // server does not use replication
1470 }
1471
1472 $conn = $this->getAnyOpenConnection( $i );
1473 $pos = $conn ? $conn->getReplicaPos() : false;
1474 if ( !$pos ) {
1475 continue; // no open connection or could not get position
1476 }
1477
1478 $highestPos = $highestPos ?: $pos;
1479 if ( $pos->hasReached( $highestPos ) ) {
1480 $highestPos = $pos;
1481 }
1482 }
1483
1484 return $highestPos;
1485 }
1486
1487 public function disable() {
1488 $this->closeAll();
1489 $this->disabled = true;
1490 }
1491
1492 public function closeAll() {
1493 $fname = __METHOD__;
1494 $this->forEachOpenConnection( function ( IDatabase $conn ) use ( $fname ) {
1495 $host = $conn->getServer();
1496 $this->connLogger->debug(
1497 $fname . ": closing connection to database '$host'." );
1498 $conn->close();
1499 } );
1500
1501 $this->conns = self::newTrackedConnectionsArray();
1502 }
1503
1504 public function closeConnection( IDatabase $conn ) {
1505 if ( $conn instanceof DBConnRef ) {
1506 // Avoid calling close() but still leaving the handle in the pool
1507 throw new RuntimeException( 'Cannot close DBConnRef instance; it must be shareable' );
1508 }
1509
1510 $serverIndex = $conn->getLBInfo( 'serverIndex' );
1511 foreach ( $this->conns as $type => $connsByServer ) {
1512 if ( !isset( $connsByServer[$serverIndex] ) ) {
1513 continue;
1514 }
1515
1516 foreach ( $connsByServer[$serverIndex] as $i => $trackedConn ) {
1517 if ( $conn === $trackedConn ) {
1518 $host = $this->getServerName( $i );
1519 $this->connLogger->debug(
1520 __METHOD__ . ": closing connection to database $i at '$host'." );
1521 unset( $this->conns[$type][$serverIndex][$i] );
1522 break 2;
1523 }
1524 }
1525 }
1526
1527 $conn->close();
1528 }
1529
1530 public function commitAll( $fname = __METHOD__, $owner = null ) {
1531 $this->commitMasterChanges( $fname, $owner );
1532 $this->flushMasterSnapshots( $fname );
1533 $this->flushReplicaSnapshots( $fname );
1534 }
1535
1536 public function finalizeMasterChanges( $fname = __METHOD__, $owner = null ) {
1537 $this->assertOwnership( $fname, $owner );
1538 $this->assertTransactionRoundStage( [ self::ROUND_CURSORY, self::ROUND_FINALIZED ] );
1539
1540 $this->trxRoundStage = self::ROUND_ERROR; // "failed" until proven otherwise
1541 // Loop until callbacks stop adding callbacks on other connections
1542 $total = 0;
1543 do {
1544 $count = 0; // callbacks execution attempts
1545 $this->forEachOpenMasterConnection( function ( Database $conn ) use ( &$count ) {
1546 // Run any pre-commit callbacks while leaving the post-commit ones suppressed.
1547 // Any error should cause all (peer) transactions to be rolled back together.
1548 $count += $conn->runOnTransactionPreCommitCallbacks();
1549 } );
1550 $total += $count;
1551 } while ( $count > 0 );
1552 // Defer post-commit callbacks until after COMMIT/ROLLBACK happens on all handles
1553 $this->forEachOpenMasterConnection( function ( Database $conn ) {
1554 $conn->setTrxEndCallbackSuppression( true );
1555 } );
1556 $this->trxRoundStage = self::ROUND_FINALIZED;
1557
1558 return $total;
1559 }
1560
1561 public function approveMasterChanges( array $options, $fname = __METHOD__, $owner = null ) {
1562 $this->assertOwnership( $fname, $owner );
1563 $this->assertTransactionRoundStage( self::ROUND_FINALIZED );
1564
1565 $limit = $options['maxWriteDuration'] ?? 0;
1566
1567 $this->trxRoundStage = self::ROUND_ERROR; // "failed" until proven otherwise
1568 $this->forEachOpenMasterConnection( function ( IDatabase $conn ) use ( $limit ) {
1569 // If atomic sections or explicit transactions are still open, some caller must have
1570 // caught an exception but failed to properly rollback any changes. Detect that and
1571 // throw and error (causing rollback).
1572 $conn->assertNoOpenTransactions();
1573 // Assert that the time to replicate the transaction will be sane.
1574 // If this fails, then all DB transactions will be rollback back together.
1575 $time = $conn->pendingWriteQueryDuration( $conn::ESTIMATE_DB_APPLY );
1576 if ( $limit > 0 && $time > $limit ) {
1577 throw new DBTransactionSizeError(
1578 $conn,
1579 "Transaction spent $time second(s) in writes, exceeding the limit of $limit",
1580 [ $time, $limit ]
1581 );
1582 }
1583 // If a connection sits idle while slow queries execute on another, that connection
1584 // may end up dropped before the commit round is reached. Ping servers to detect this.
1585 if ( $conn->writesOrCallbacksPending() && !$conn->ping() ) {
1586 throw new DBTransactionError(
1587 $conn,
1588 "A connection to the {$conn->getDBname()} database was lost before commit"
1589 );
1590 }
1591 } );
1592 $this->trxRoundStage = self::ROUND_APPROVED;
1593 }
1594
1595 public function beginMasterChanges( $fname = __METHOD__, $owner = null ) {
1596 $this->assertOwnership( $fname, $owner );
1597 if ( $this->trxRoundId !== false ) {
1598 throw new DBTransactionError(
1599 null,
1600 "$fname: Transaction round '{$this->trxRoundId}' already started"
1601 );
1602 }
1603 $this->assertTransactionRoundStage( self::ROUND_CURSORY );
1604
1605 // Clear any empty transactions (no writes/callbacks) from the implicit round
1606 $this->flushMasterSnapshots( $fname );
1607
1608 $this->trxRoundId = $fname;
1609 $this->trxRoundStage = self::ROUND_ERROR; // "failed" until proven otherwise
1610 // Mark applicable handles as participating in this explicit transaction round.
1611 // For each of these handles, any writes and callbacks will be tied to a single
1612 // transaction. The (peer) handles will reject begin()/commit() calls unless they
1613 // are part of an en masse commit or an en masse rollback.
1614 $this->forEachOpenMasterConnection( function ( Database $conn ) {
1615 $this->applyTransactionRoundFlags( $conn );
1616 } );
1617 $this->trxRoundStage = self::ROUND_CURSORY;
1618 }
1619
1620 public function commitMasterChanges( $fname = __METHOD__, $owner = null ) {
1621 $this->assertOwnership( $fname, $owner );
1622 $this->assertTransactionRoundStage( self::ROUND_APPROVED );
1623
1624 $failures = [];
1625
1626 /** @noinspection PhpUnusedLocalVariableInspection */
1627 $scope = ScopedCallback::newScopedIgnoreUserAbort(); // try to ignore client aborts
1628
1629 $restore = ( $this->trxRoundId !== false );
1630 $this->trxRoundId = false;
1631 $this->trxRoundStage = self::ROUND_ERROR; // "failed" until proven otherwise
1632 // Commit any writes and clear any snapshots as well (callbacks require AUTOCOMMIT).
1633 // Note that callbacks should already be suppressed due to finalizeMasterChanges().
1634 $this->forEachOpenMasterConnection(
1635 function ( IDatabase $conn ) use ( $fname, &$failures ) {
1636 try {
1637 $conn->commit( $fname, $conn::FLUSHING_ALL_PEERS );
1638 } catch ( DBError $e ) {
1639 ( $this->errorLogger )( $e );
1640 $failures[] = "{$conn->getServer()}: {$e->getMessage()}";
1641 }
1642 }
1643 );
1644 if ( $failures ) {
1645 throw new DBTransactionError(
1646 null,
1647 "$fname: Commit failed on server(s) " . implode( "\n", array_unique( $failures ) )
1648 );
1649 }
1650 if ( $restore ) {
1651 // Unmark handles as participating in this explicit transaction round
1652 $this->forEachOpenMasterConnection( function ( Database $conn ) {
1653 $this->undoTransactionRoundFlags( $conn );
1654 } );
1655 }
1656 $this->trxRoundStage = self::ROUND_COMMIT_CALLBACKS;
1657 }
1658
1659 public function runMasterTransactionIdleCallbacks( $fname = __METHOD__, $owner = null ) {
1660 $this->assertOwnership( $fname, $owner );
1661 if ( $this->trxRoundStage === self::ROUND_COMMIT_CALLBACKS ) {
1662 $type = IDatabase::TRIGGER_COMMIT;
1663 } elseif ( $this->trxRoundStage === self::ROUND_ROLLBACK_CALLBACKS ) {
1664 $type = IDatabase::TRIGGER_ROLLBACK;
1665 } else {
1666 throw new DBTransactionError(
1667 null,
1668 "Transaction should be in the callback stage (not '{$this->trxRoundStage}')"
1669 );
1670 }
1671
1672 $oldStage = $this->trxRoundStage;
1673 $this->trxRoundStage = self::ROUND_ERROR; // "failed" until proven otherwise
1674
1675 // Now that the COMMIT/ROLLBACK step is over, enable post-commit callback runs
1676 $this->forEachOpenMasterConnection( function ( Database $conn ) {
1677 $conn->setTrxEndCallbackSuppression( false );
1678 } );
1679
1680 $e = null; // first exception
1681 $fname = __METHOD__;
1682 // Loop until callbacks stop adding callbacks on other connections
1683 do {
1684 // Run any pending callbacks for each connection...
1685 $count = 0; // callback execution attempts
1686 $this->forEachOpenMasterConnection(
1687 function ( Database $conn ) use ( $type, &$e, &$count ) {
1688 if ( $conn->trxLevel() ) {
1689 return; // retry in the next iteration, after commit() is called
1690 }
1691 try {
1692 $count += $conn->runOnTransactionIdleCallbacks( $type );
1693 } catch ( Exception $ex ) {
1694 $e = $e ?: $ex;
1695 }
1696 }
1697 );
1698 // Clear out any active transactions left over from callbacks...
1699 $this->forEachOpenMasterConnection( function ( Database $conn ) use ( &$e, $fname ) {
1700 if ( $conn->writesPending() ) {
1701 // A callback from another handle wrote to this one and DBO_TRX is set
1702 $this->queryLogger->warning( $fname . ": found writes pending." );
1703 $fnames = implode( ', ', $conn->pendingWriteAndCallbackCallers() );
1704 $this->queryLogger->warning(
1705 $fname . ": found writes pending ($fnames).",
1706 [
1707 'db_server' => $conn->getServer(),
1708 'db_name' => $conn->getDBname()
1709 ]
1710 );
1711 } elseif ( $conn->trxLevel() ) {
1712 // A callback from another handle read from this one and DBO_TRX is set,
1713 // which can easily happen if there is only one DB (no replicas)
1714 $this->queryLogger->debug( $fname . ": found empty transaction." );
1715 }
1716 try {
1717 $conn->commit( $fname, $conn::FLUSHING_ALL_PEERS );
1718 } catch ( Exception $ex ) {
1719 $e = $e ?: $ex;
1720 }
1721 } );
1722 } while ( $count > 0 );
1723
1724 $this->trxRoundStage = $oldStage;
1725
1726 return $e;
1727 }
1728
1729 public function runMasterTransactionListenerCallbacks( $fname = __METHOD__, $owner = null ) {
1730 $this->assertOwnership( $fname, $owner );
1731 if ( $this->trxRoundStage === self::ROUND_COMMIT_CALLBACKS ) {
1732 $type = IDatabase::TRIGGER_COMMIT;
1733 } elseif ( $this->trxRoundStage === self::ROUND_ROLLBACK_CALLBACKS ) {
1734 $type = IDatabase::TRIGGER_ROLLBACK;
1735 } else {
1736 throw new DBTransactionError(
1737 null,
1738 "Transaction should be in the callback stage (not '{$this->trxRoundStage}')"
1739 );
1740 }
1741
1742 $e = null;
1743
1744 $this->trxRoundStage = self::ROUND_ERROR; // "failed" until proven otherwise
1745 $this->forEachOpenMasterConnection( function ( Database $conn ) use ( $type, &$e ) {
1746 try {
1747 $conn->runTransactionListenerCallbacks( $type );
1748 } catch ( Exception $ex ) {
1749 $e = $e ?: $ex;
1750 }
1751 } );
1752 $this->trxRoundStage = self::ROUND_CURSORY;
1753
1754 return $e;
1755 }
1756
1757 public function rollbackMasterChanges( $fname = __METHOD__, $owner = null ) {
1758 $this->assertOwnership( $fname, $owner );
1759
1760 $restore = ( $this->trxRoundId !== false );
1761 $this->trxRoundId = false;
1762 $this->trxRoundStage = self::ROUND_ERROR; // "failed" until proven otherwise
1763 $this->forEachOpenMasterConnection( function ( IDatabase $conn ) use ( $fname ) {
1764 $conn->rollback( $fname, $conn::FLUSHING_ALL_PEERS );
1765 } );
1766 if ( $restore ) {
1767 // Unmark handles as participating in this explicit transaction round
1768 $this->forEachOpenMasterConnection( function ( Database $conn ) {
1769 $this->undoTransactionRoundFlags( $conn );
1770 } );
1771 }
1772 $this->trxRoundStage = self::ROUND_ROLLBACK_CALLBACKS;
1773 }
1774
1775 /**
1776 * @param string|string[] $stage
1777 * @throws DBTransactionError
1778 */
1779 private function assertTransactionRoundStage( $stage ) {
1780 $stages = (array)$stage;
1781
1782 if ( !in_array( $this->trxRoundStage, $stages, true ) ) {
1783 $stageList = implode(
1784 '/',
1785 array_map( function ( $v ) {
1786 return "'$v'";
1787 }, $stages )
1788 );
1789 throw new DBTransactionError(
1790 null,
1791 "Transaction round stage must be $stageList (not '{$this->trxRoundStage}')"
1792 );
1793 }
1794 }
1795
1796 /**
1797 * @param string $fname
1798 * @param int|null $owner Owner ID of the caller
1799 * @throws DBTransactionError
1800 */
1801 private function assertOwnership( $fname, $owner ) {
1802 if ( $this->ownerId !== null && $owner !== $this->ownerId ) {
1803 throw new DBTransactionError(
1804 null,
1805 "$fname: LoadBalancer is owned by LBFactory #{$this->ownerId} (got '$owner')."
1806 );
1807 }
1808 }
1809
1810 /**
1811 * Make all DB servers with DBO_DEFAULT/DBO_TRX set join the transaction round
1812 *
1813 * Some servers may have neither flag enabled, meaning that they opt out of such
1814 * transaction rounds and remain in auto-commit mode. Such behavior might be desired
1815 * when a DB server is used for something like simple key/value storage.
1816 *
1817 * @param Database $conn
1818 */
1819 private function applyTransactionRoundFlags( Database $conn ) {
1820 if ( $conn->getLBInfo( 'autoCommitOnly' ) ) {
1821 return; // transaction rounds do not apply to these connections
1822 }
1823
1824 if ( $conn->getFlag( $conn::DBO_DEFAULT ) ) {
1825 // DBO_TRX is controlled entirely by CLI mode presence with DBO_DEFAULT.
1826 // Force DBO_TRX even in CLI mode since a commit round is expected soon.
1827 $conn->setFlag( $conn::DBO_TRX, $conn::REMEMBER_PRIOR );
1828 }
1829
1830 if ( $conn->getFlag( $conn::DBO_TRX ) ) {
1831 $conn->setLBInfo( 'trxRoundId', $this->trxRoundId );
1832 }
1833 }
1834
1835 /**
1836 * @param Database $conn
1837 */
1838 private function undoTransactionRoundFlags( Database $conn ) {
1839 if ( $conn->getLBInfo( 'autoCommitOnly' ) ) {
1840 return; // transaction rounds do not apply to these connections
1841 }
1842
1843 if ( $conn->getFlag( $conn::DBO_TRX ) ) {
1844 $conn->setLBInfo( 'trxRoundId', null ); // remove the round ID
1845 }
1846
1847 if ( $conn->getFlag( $conn::DBO_DEFAULT ) ) {
1848 $conn->restoreFlags( $conn::RESTORE_PRIOR );
1849 }
1850 }
1851
1852 public function flushReplicaSnapshots( $fname = __METHOD__ ) {
1853 $this->forEachOpenReplicaConnection( function ( IDatabase $conn ) use ( $fname ) {
1854 $conn->flushSnapshot( $fname );
1855 } );
1856 }
1857
1858 public function flushMasterSnapshots( $fname = __METHOD__ ) {
1859 $this->forEachOpenMasterConnection( function ( IDatabase $conn ) use ( $fname ) {
1860 $conn->flushSnapshot( $fname );
1861 } );
1862 }
1863
1864 /**
1865 * @return string
1866 * @since 1.32
1867 */
1868 public function getTransactionRoundStage() {
1869 return $this->trxRoundStage;
1870 }
1871
1872 public function hasMasterConnection() {
1873 return $this->isOpen( $this->getWriterIndex() );
1874 }
1875
1876 public function hasMasterChanges() {
1877 $pending = 0;
1878 $this->forEachOpenMasterConnection( function ( IDatabase $conn ) use ( &$pending ) {
1879 $pending |= $conn->writesOrCallbacksPending();
1880 } );
1881
1882 return (bool)$pending;
1883 }
1884
1885 public function lastMasterChangeTimestamp() {
1886 $lastTime = false;
1887 $this->forEachOpenMasterConnection( function ( IDatabase $conn ) use ( &$lastTime ) {
1888 $lastTime = max( $lastTime, $conn->lastDoneWrites() );
1889 } );
1890
1891 return $lastTime;
1892 }
1893
1894 public function hasOrMadeRecentMasterChanges( $age = null ) {
1895 $age = ( $age === null ) ? $this->waitTimeout : $age;
1896
1897 return ( $this->hasMasterChanges()
1898 || $this->lastMasterChangeTimestamp() > microtime( true ) - $age );
1899 }
1900
1901 public function pendingMasterChangeCallers() {
1902 $fnames = [];
1903 $this->forEachOpenMasterConnection( function ( IDatabase $conn ) use ( &$fnames ) {
1904 $fnames = array_merge( $fnames, $conn->pendingWriteCallers() );
1905 } );
1906
1907 return $fnames;
1908 }
1909
1910 public function getLaggedReplicaMode( $domain = false ) {
1911 if ( $this->laggedReplicaMode ) {
1912 return true; // stay in lagged replica mode
1913 }
1914
1915 if ( $this->hasStreamingReplicaServers() ) {
1916 // This will set "laggedReplicaMode" as needed
1917 $this->getReaderIndex( self::GROUP_GENERIC, $domain );
1918 }
1919
1920 return $this->laggedReplicaMode;
1921 }
1922
1923 public function laggedReplicaUsed() {
1924 return $this->laggedReplicaMode;
1925 }
1926
1927 public function getReadOnlyReason( $domain = false, IDatabase $conn = null ) {
1928 if ( $this->readOnlyReason !== false ) {
1929 return $this->readOnlyReason;
1930 } elseif ( $this->masterRunningReadOnly( $domain, $conn ) ) {
1931 return 'The master database server is running in read-only mode.';
1932 } elseif ( $this->getLaggedReplicaMode( $domain ) ) {
1933 return ( $this->getExistingReaderIndex( self::GROUP_GENERIC ) >= 0 )
1934 ? 'The database is read-only until replication lag decreases.'
1935 : 'The database is read-only until a replica database server becomes reachable.';
1936 }
1937
1938 return false;
1939 }
1940
1941 /**
1942 * @param string $domain Domain ID, or false for the current domain
1943 * @param IDatabase|null $conn DB master connectionl used to avoid loops [optional]
1944 * @return bool
1945 */
1946 private function masterRunningReadOnly( $domain, IDatabase $conn = null ) {
1947 $cache = $this->wanCache;
1948 $masterServer = $this->getServerName( $this->getWriterIndex() );
1949
1950 return (bool)$cache->getWithSetCallback(
1951 $cache->makeGlobalKey( __CLASS__, 'server-read-only', $masterServer ),
1952 self::TTL_CACHE_READONLY,
1953 function () use ( $domain, $conn ) {
1954 $old = $this->trxProfiler->setSilenced( true );
1955 try {
1956 $index = $this->getWriterIndex();
1957 $dbw = $conn ?: $this->getServerConnection( $index, $domain );
1958 $readOnly = (int)$dbw->serverIsReadOnly();
1959 if ( !$conn ) {
1960 $this->reuseConnection( $dbw );
1961 }
1962 } catch ( DBError $e ) {
1963 $readOnly = 0;
1964 }
1965 $this->trxProfiler->setSilenced( $old );
1966
1967 return $readOnly;
1968 },
1969 [ 'pcTTL' => $cache::TTL_PROC_LONG, 'busyValue' => 0 ]
1970 );
1971 }
1972
1973 public function allowLagged( $mode = null ) {
1974 if ( $mode === null ) {
1975 return $this->allowLagged;
1976 }
1977 $this->allowLagged = $mode;
1978
1979 return $this->allowLagged;
1980 }
1981
1982 public function pingAll() {
1983 $success = true;
1984 $this->forEachOpenConnection( function ( IDatabase $conn ) use ( &$success ) {
1985 if ( !$conn->ping() ) {
1986 $success = false;
1987 }
1988 } );
1989
1990 return $success;
1991 }
1992
1993 public function forEachOpenConnection( $callback, array $params = [] ) {
1994 foreach ( $this->conns as $connsByServer ) {
1995 foreach ( $connsByServer as $serverConns ) {
1996 foreach ( $serverConns as $conn ) {
1997 $callback( $conn, ...$params );
1998 }
1999 }
2000 }
2001 }
2002
2003 public function forEachOpenMasterConnection( $callback, array $params = [] ) {
2004 $masterIndex = $this->getWriterIndex();
2005 foreach ( $this->conns as $connsByServer ) {
2006 if ( isset( $connsByServer[$masterIndex] ) ) {
2007 /** @var IDatabase $conn */
2008 foreach ( $connsByServer[$masterIndex] as $conn ) {
2009 $callback( $conn, ...$params );
2010 }
2011 }
2012 }
2013 }
2014
2015 public function forEachOpenReplicaConnection( $callback, array $params = [] ) {
2016 foreach ( $this->conns as $connsByServer ) {
2017 foreach ( $connsByServer as $i => $serverConns ) {
2018 if ( $i === $this->getWriterIndex() ) {
2019 continue; // skip master
2020 }
2021 foreach ( $serverConns as $conn ) {
2022 $callback( $conn, ...$params );
2023 }
2024 }
2025 }
2026 }
2027
2028 /**
2029 * @return int
2030 */
2031 private function getCurrentConnectionCount() {
2032 $count = 0;
2033 foreach ( $this->conns as $connsByServer ) {
2034 foreach ( $connsByServer as $serverConns ) {
2035 $count += count( $serverConns );
2036 }
2037 }
2038
2039 return $count;
2040 }
2041
2042 public function getMaxLag( $domain = false ) {
2043 $host = '';
2044 $maxLag = -1;
2045 $maxIndex = 0;
2046
2047 if ( $this->hasReplicaServers() ) {
2048 $lagTimes = $this->getLagTimes( $domain );
2049 foreach ( $lagTimes as $i => $lag ) {
2050 if ( $this->groupLoads[self::GROUP_GENERIC][$i] > 0 && $lag > $maxLag ) {
2051 $maxLag = $lag;
2052 $host = $this->getServerInfoStrict( $i, 'host' );
2053 $maxIndex = $i;
2054 }
2055 }
2056 }
2057
2058 return [ $host, $maxLag, $maxIndex ];
2059 }
2060
2061 public function getLagTimes( $domain = false ) {
2062 if ( !$this->hasReplicaServers() ) {
2063 return [ $this->getWriterIndex() => 0 ]; // no replication = no lag
2064 }
2065
2066 $knownLagTimes = []; // map of (server index => 0 seconds)
2067 $indexesWithLag = [];
2068 foreach ( $this->servers as $i => $server ) {
2069 if ( empty( $server['is static'] ) ) {
2070 $indexesWithLag[] = $i; // DB server might have replication lag
2071 } else {
2072 $knownLagTimes[$i] = 0; // DB server is a non-replicating and read-only archive
2073 }
2074 }
2075
2076 return $this->getLoadMonitor()->getLagTimes( $indexesWithLag, $domain ) + $knownLagTimes;
2077 }
2078
2079 /**
2080 * Get the lag in seconds for a given connection, or zero if this load
2081 * balancer does not have replication enabled.
2082 *
2083 * This should be used in preference to Database::getLag() in cases where
2084 * replication may not be in use, since there is no way to determine if
2085 * replication is in use at the connection level without running
2086 * potentially restricted queries such as SHOW SLAVE STATUS. Using this
2087 * function instead of Database::getLag() avoids a fatal error in this
2088 * case on many installations.
2089 *
2090 * @param IDatabase $conn
2091 * @return int|bool Returns false on error
2092 * @deprecated Since 1.34 Use IDatabase::getLag() instead
2093 */
2094 public function safeGetLag( IDatabase $conn ) {
2095 if ( $conn->getLBInfo( 'is static' ) ) {
2096 return 0; // static dataset
2097 } elseif ( $conn->getLBInfo( 'serverIndex' ) == $this->getWriterIndex() ) {
2098 return 0; // this is the master
2099 }
2100
2101 return $conn->getLag();
2102 }
2103
2104 public function waitForMasterPos( IDatabase $conn, $pos = false, $timeout = null ) {
2105 $timeout = max( 1, $timeout ?: $this->waitTimeout );
2106
2107 if ( $conn->getLBInfo( 'serverIndex' ) === $this->getWriterIndex() ) {
2108 return true; // not a replica DB server
2109 }
2110
2111 if ( !$pos ) {
2112 // Get the current master position, opening a connection if needed
2113 $index = $this->getWriterIndex();
2114 $flags = self::CONN_SILENCE_ERRORS;
2115 $masterConn = $this->getAnyOpenConnection( $index, $flags );
2116 if ( $masterConn ) {
2117 $pos = $masterConn->getMasterPos();
2118 } else {
2119 $masterConn = $this->getServerConnection( $index, self::DOMAIN_ANY, $flags );
2120 if ( !$masterConn ) {
2121 throw new DBReplicationWaitError(
2122 null,
2123 "Could not obtain a master database connection to get the position"
2124 );
2125 }
2126 $pos = $masterConn->getMasterPos();
2127 $this->closeConnection( $masterConn );
2128 }
2129 }
2130
2131 if ( $pos instanceof DBMasterPos ) {
2132 $start = microtime( true );
2133 $result = $conn->masterPosWait( $pos, $timeout );
2134 $seconds = max( microtime( true ) - $start, 0 );
2135 if ( $result == -1 || is_null( $result ) ) {
2136 $msg = __METHOD__ . ': timed out waiting on {host} pos {pos} [{seconds}s]';
2137 $this->replLogger->warning( $msg, [
2138 'host' => $conn->getServer(),
2139 'pos' => $pos,
2140 'seconds' => round( $seconds, 6 ),
2141 'trace' => ( new RuntimeException() )->getTraceAsString()
2142 ] );
2143 $ok = false;
2144 } else {
2145 $this->replLogger->debug( __METHOD__ . ': done waiting' );
2146 $ok = true;
2147 }
2148 } else {
2149 $ok = false; // something is misconfigured
2150 $this->replLogger->error(
2151 __METHOD__ . ': could not get master pos for {host}',
2152 [
2153 'host' => $conn->getServer(),
2154 'trace' => ( new RuntimeException() )->getTraceAsString()
2155 ]
2156 );
2157 }
2158
2159 return $ok;
2160 }
2161
2162 /**
2163 * Wait for a replica DB to reach a specified master position
2164 *
2165 * This will connect to the master to get an accurate position if $pos is not given
2166 *
2167 * @param IDatabase $conn Replica DB
2168 * @param DBMasterPos|bool $pos Master position; default: current position
2169 * @param int $timeout Timeout in seconds [optional]
2170 * @return bool Success
2171 * @since 1.28
2172 * @deprecated Since 1.34 Use waitForMasterPos() instead
2173 */
2174 public function safeWaitForMasterPos( IDatabase $conn, $pos = false, $timeout = null ) {
2175 return $this->waitForMasterPos( $conn, $pos, $timeout );
2176 }
2177
2178 public function setTransactionListener( $name, callable $callback = null ) {
2179 if ( $callback ) {
2180 $this->trxRecurringCallbacks[$name] = $callback;
2181 } else {
2182 unset( $this->trxRecurringCallbacks[$name] );
2183 }
2184 $this->forEachOpenMasterConnection(
2185 function ( IDatabase $conn ) use ( $name, $callback ) {
2186 $conn->setTransactionListener( $name, $callback );
2187 }
2188 );
2189 }
2190
2191 public function setTableAliases( array $aliases ) {
2192 $this->tableAliases = $aliases;
2193 }
2194
2195 public function setIndexAliases( array $aliases ) {
2196 $this->indexAliases = $aliases;
2197 }
2198
2199 public function setLocalDomainPrefix( $prefix ) {
2200 // Find connections to explicit foreign domains still marked as in-use...
2201 $domainsInUse = [];
2202 $this->forEachOpenConnection( function ( IDatabase $conn ) use ( &$domainsInUse ) {
2203 // Once reuseConnection() is called on a handle, its reference count goes from 1 to 0.
2204 // Until then, it is still in use by the caller (explicitly or via DBConnRef scope).
2205 if ( $conn->getLBInfo( 'foreignPoolRefCount' ) > 0 ) {
2206 $domainsInUse[] = $conn->getDomainID();
2207 }
2208 } );
2209
2210 // Do not switch connections to explicit foreign domains unless marked as safe
2211 if ( $domainsInUse ) {
2212 $domains = implode( ', ', $domainsInUse );
2213 throw new DBUnexpectedError( null,
2214 "Foreign domain connections are still in use ($domains)" );
2215 }
2216
2217 $this->setLocalDomain( new DatabaseDomain(
2218 $this->localDomain->getDatabase(),
2219 $this->localDomain->getSchema(),
2220 $prefix
2221 ) );
2222
2223 // Update the prefix for all local connections...
2224 $this->forEachOpenConnection( function ( IDatabase $conn ) use ( $prefix ) {
2225 if ( !$conn->getLBInfo( 'foreign' ) ) {
2226 $conn->tablePrefix( $prefix );
2227 }
2228 } );
2229 }
2230
2231 public function redefineLocalDomain( $domain ) {
2232 $this->closeAll();
2233
2234 $this->setLocalDomain( DatabaseDomain::newFromId( $domain ) );
2235 }
2236
2237 /**
2238 * @param DatabaseDomain $domain
2239 */
2240 private function setLocalDomain( DatabaseDomain $domain ) {
2241 $this->localDomain = $domain;
2242 // In case a caller assumes that the domain ID is simply <db>-<prefix>, which is almost
2243 // always true, gracefully handle the case when they fail to account for escaping.
2244 if ( $this->localDomain->getTablePrefix() != '' ) {
2245 $this->localDomainIdAlias =
2246 $this->localDomain->getDatabase() . '-' . $this->localDomain->getTablePrefix();
2247 } else {
2248 $this->localDomainIdAlias = $this->localDomain->getDatabase();
2249 }
2250 }
2251
2252 /**
2253 * @param int $i Server index
2254 * @param string|null $field Server index field [optional]
2255 * @return array|mixed
2256 * @throws InvalidArgumentException
2257 */
2258 private function getServerInfoStrict( $i, $field = null ) {
2259 if ( !isset( $this->servers[$i] ) || !is_array( $this->servers[$i] ) ) {
2260 throw new InvalidArgumentException( "No server with index '$i'" );
2261 }
2262
2263 if ( $field !== null ) {
2264 if ( !array_key_exists( $field, $this->servers[$i] ) ) {
2265 throw new InvalidArgumentException( "No field '$field' in server index '$i'" );
2266 }
2267
2268 return $this->servers[$i][$field];
2269 }
2270
2271 return $this->servers[$i];
2272 }
2273
2274 function __destruct() {
2275 // Avoid connection leaks for sanity
2276 $this->disable();
2277 }
2278 }
2279
2280 /**
2281 * @deprecated since 1.29
2282 */
2283 class_alias( LoadBalancer::class, 'LoadBalancer' );